package com.farm.project.service.impl;

import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectType;
import com.farm.project.domain.TaskLog;
import com.farm.project.domain.TaskType;
import com.farm.core.time.TimeTool;
import com.farm.file.WdapFileServiceInter;
import com.farm.file.domain.FileBase;
import com.farm.file.domain.ex.PersistFile;
import com.farm.file.util.FarmDocFiles;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.farm.project.dao.FieldReTtypeDaoInter;
import com.farm.project.dao.ProjectGradationTasktypeDaoInter;
import com.farm.project.dao.TaskTypeDaoInter;
import com.farm.project.service.TaskTypeServiceInter;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：任务类型服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class TaskTypeServiceImpl implements TaskTypeServiceInter {
	@Resource
	private TaskTypeDaoInter tasktypeDaoImpl;
	@Resource
	private FieldReTtypeDaoInter fieldrettypeDaoImpl;
	@Resource
	private ProjectGradationTasktypeDaoInter projectgradationtasktypeDaoImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	private static final Logger log = Logger.getLogger(TaskTypeServiceImpl.class);

	@Override
	@Transactional
	public TaskType insertTasktypeEntity(TaskType entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		entity.setUuid("NONE");
		if (StringUtils.isBlank(entity.getParentid())) {
			entity.setParentid("NONE");
		}
		entity.setTreecode("NONE");
		entity = tasktypeDaoImpl.insertEntity(entity);
		entity.setUuid(entity.getId());
		initTreeCode(entity.getId());
		tasktypeDaoImpl.editEntity(entity);
		return entity;
	}

	private void initTreeCode(String treeNodeId) {
		TaskType node = getTasktypeEntity(treeNodeId);
		if (node.getParentid().equals("NONE")) {
			node.setTreecode(node.getId());
		} else {
			node.setTreecode(tasktypeDaoImpl.getEntity(node.getParentid()).getTreecode() + node.getId());
		}
		tasktypeDaoImpl.editEntity(node);
	}

	@Override
	@Transactional
	public TaskType editTasktypeEntity(TaskType entity, LoginUser user) {
		TaskType entity2 = tasktypeDaoImpl.getEntity(entity.getId());
		entity2.setName(entity.getName());
		entity2.setSort(entity.getSort());
		entity2.setPcontent(entity.getPcontent());
		entity2.setPstate(entity.getPstate());
		entity2.setModel(entity.getModel());
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		tasktypeDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteTasktypeEntity(String id, LoginUser user) {
		if (tasktypeDaoImpl.selectEntitys(DBRule.addRule(new ArrayList<DBRule>(), "parentid", id, "=")).size() > 0) {
			throw new RuntimeException("不能删除该节点，请先删除其子节点");
		}
		TaskType tasktype = tasktypeDaoImpl.getEntity(id);
		if (tasktype.getUuid().equals(tasktype.getId())) {
			tasktype.setPstate("2");
			tasktype.setEtime(TimeTool.getTimeDate14());
			tasktype.setEuser(user.getId());
			tasktypeDaoImpl.editEntity(tasktype);
		} else {
			tasktypeDaoImpl.deleteEntity(tasktype);
		}
	}

	@Override
	@Transactional
	public TaskType getTasktypeEntity(String id) {
		if (id == null) {
			return null;
		}
		return tasktypeDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createTasktypeSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "PLOGS_TASK_TYPE",
				"ID,SORT,NAME,PCONTENT,MODEL,MODEL as MODELVAL,PSTATE,EUSER,CUSER,ETIME,CTIME,UUID,TEMPLETEFILEID");
		return dbQuery;
	}

	@Override
	@Transactional
	public void editSort(String id, int sort, LoginUser currentUser) {
		TaskType entity2 = tasktypeDaoImpl.getEntity(id);
		entity2.setSort(sort);
		tasktypeDaoImpl.editEntity(entity2);
	}

	@Override
	@Transactional
	public void moveTreeNode(String ids, String targetId, LoginUser currentUser) {
		String[] idArray = ids.split(",");
		TaskType target = getTasktypeEntity(targetId);
		if (target != null && target.getModel().equals("1")) {
			throw new RuntimeException("'类型'节点下禁止创建子节点!");
		}
		for (int i = 0; i < idArray.length; i++) {
			// 移动节点
			TaskType node = getTasktypeEntity(idArray[i]);
			if (target != null && target.getTreecode().indexOf(node.getTreecode()) >= 0) {
				throw new RuntimeException("不能够移动到其子节点下!");
			}
			if (target == null) {
				node.setParentid("NONE");
			} else {
				node.setParentid(targetId);
			}
			tasktypeDaoImpl.editEntity(node);
			// 构造所有树TREECODE
			List<TaskType> list = tasktypeDaoImpl.getAllSubNodes(idArray[i]);
			for (TaskType org : list) {
				initTreeCode(org.getId());
			}
		}
	}

	@Override
	@Transactional
	public void saveTemplete(String taskTypeid, String text, LoginUser currentUser) throws IOException {
		if (text == null || text.trim().length() <= 0) {
			return;
		}
		TaskType ttype = tasktypeDaoImpl.getEntity(taskTypeid);
		String fileName = "任务分类模板-" + TimeTool.format(new Date(), "yyyy年MM月dd日") + ".ihtml";
		ttype.setTempletefileid(prisistTextToFile(ttype.getTempletefileid(), text, fileName, currentUser).getId());
		tasktypeDaoImpl.editEntity(ttype);
		if (StringUtils.isNotBlank(ttype.getTempletefileid())) {
			wdapFileServiceImpl.submitFile(ttype.getTempletefileid());
			prisistTextFiles(text);
		}
	}

	/**
	 * 保存富文本为一个文件对象
	 * 
	 * @param fileId
	 *            為空時創建，不爲空時修改
	 * @param text
	 * @param fileName
	 * @param currentUser
	 * @return
	 * @throws IOException
	 */
	private FileBase prisistTextToFile(String fileId, String text, String fileName, LoginUser currentUser)
			throws IOException {
		FileBase file = null;
		if (StringUtils.isNotBlank(fileId)) {
			// 更新文件
			file = wdapFileServiceImpl.getFileBase(fileId);
			wdapFileServiceImpl.updateFilesize(fileId, text.length());
		}
		if (file == null) {
			// 创建文件
			file = wdapFileServiceImpl.initFile(currentUser, fileName, text.length(), null, "PLOGS");
		}
		wdapFileServiceImpl.WriteTextFile(file.getId(), text, currentUser);
		return file;
	}

	/**
	 * 持久化富文本中的附件
	 * 
	 * @param text
	 * @throws FileNotFoundException
	 */
	private List<FileBase> prisistTextFiles(String text) throws FileNotFoundException {
		if (StringUtils.isBlank(text)) {
			return new ArrayList<>();
		}
		List<FileBase> backfiles = new ArrayList<>();
		List<String> files = FarmDocFiles.getFilesIdFromHtml(text);
		for (String fileid : files) {
			backfiles.add(wdapFileServiceImpl.getFileBase(fileid));
		}
		return backfiles;
	}

	@Override
	@Transactional
	public String readTempleteHtml(String taskTypeid) {
		TaskType ttype = tasktypeDaoImpl.getEntity(taskTypeid);
		if (ttype != null && ttype.getTempletefileid() != null) {
			PersistFile pfile = wdapFileServiceImpl.getPersistFile(ttype.getTempletefileid());
			String text = FarmDocFiles.readFileText(pfile.getFile());
			return text;
		}
		return null;
	}

	@Override
	@Transactional
	public void clearTemplete(String taskTypeid, LoginUser currentUser) {
		TaskType ttype = tasktypeDaoImpl.getEntity(taskTypeid);
		if (ttype.getTempletefileid() != null) {
			wdapFileServiceImpl.freeFile(ttype.getTempletefileid());
		}
		ttype.setTempletefileid(null);
		tasktypeDaoImpl.editEntity(ttype);
	}
}
